package com.fingard.dsp.bank.directbank.bob01;

import java.util.Date;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.PaymentState;
import com.fingard.dsp.bank.directbank.bankInterface.ISinglePay;
import com.fingard.dsp.bank.reqrespobj.single.*;
import com.fingard.dsp.bank.reqrespobj.single.detail.RetAtsSglDetail;
import com.fingard.net.ConnState;
import com.fingard.text.StringHelper;
import com.fingard.xml.XElement;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

public class BOB01SinglePay extends BOB01Base implements ISinglePay {

    //单笔支付，不需采用流处理方式
    public RetAtsSingle d_1908_SglPay(ReqSingle p_req1908) throws Exception {
        //返回ATS的对象
        RetAtsSingle retAts = new RetAtsSingle(p_req1908.reqHeader);
        RetAtsSglDetail tmpRetDetail;
        tmpRetDetail = d_190802(p_req1908);

        if (tmpRetDetail.respCode.equals("-1") && StringHelper.isNullOrEmpty(tmpRetDetail.reqSeqID)) {
            tmpRetDetail.reqSeqID = p_req1908.singleDetail.askNumber;
        }
        retAts.writeRetDetail(tmpRetDetail);
        return retAts;
    }

    @Override
    public RetAtsSingleBat d_1908BAT_SglBatPay(ReqSingleBat p_req1908BAT) throws Exception {
        return null;
    }

    //190802对外支付
    private RetAtsSglDetail d_190802(ReqSingle p_req1908) throws Exception {
        RetAtsSglDetail retDetail = new RetAtsSglDetail();
        //赋值通用参数

        XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
        xmlWriter.autoFormat = false;//报文串需要整个字符串传送，中间需无回车符，否则会签名出错

        writeCommonHeader(xmlWriter);

        String opName = "CebankPayWithNewPrecontractOp";
        xmlWriter.writeStartElement("opReq");
        xmlWriter.writeElementString("opName", opName);
        xmlWriter.writeElementString("serialNo", p_req1908.singleDetail.askNumber);
        xmlWriter.writeElementString("reqTime", Format.Date8Format.format(new Date()));
        XElement tmpXElement = new XElement("ReqParam", "");
        tmpXElement.addChild(new XElement("payEnpName", p_req1908.singleDetail.payName));
        tmpXElement.addChild(new XElement("payAcct", p_req1908.singleDetail.payAct));
        tmpXElement.addChild(new XElement("recAcct", p_req1908.singleDetail.recAct));
        tmpXElement.addChild(new XElement("recAcctName", p_req1908.singleDetail.recName));
        tmpXElement.addChild(new XElement("recProvince", ""));
        tmpXElement.addChild(new XElement("recCity", ""));
        tmpXElement.addChild(new XElement("recBankName", p_req1908.singleDetail.cnapsName));
        tmpXElement.addChild(new XElement("recBankNo", ""));
        tmpXElement.addChild(new XElement("amount", p_req1908.singleDetail.payAmount.replaceAll("\\.", "")));
        tmpXElement.addChild(new XElement("payUse", p_req1908.singleDetail.purpose));
        tmpXElement.addChild(new XElement("remark", p_req1908.singleDetail.abstractATS));
        //0：本行;1：它行同城，（同城交换）;2：它行异地，（电汇）
        /*行内转账时传0，
        1：同城交换，（免费）
		2：电汇，（快）
		说明：行内转账时必须传0，
		它行同城转账时可以选同城交换也可以选电汇，
		它行异地转账时只能选电汇*/
        if (p_req1908.singleDetail.sameBnk.equals("1")) {
            tmpXElement.addChild(new XElement("transFlag", "0"));
            tmpXElement.addChild(new XElement("transmitType", "0"));
        } else {
            if ("1".equals(getBankConfig().getValueAsString("transFlag"))) {//不使用同城票交直接电汇
                tmpXElement.addChild(new XElement("transFlag", "2"));
                tmpXElement.addChild(new XElement("transmitType", "2"));
            } else {
                if (p_req1908.singleDetail.sameCity.equals("1")) {
                    //同城票交，免费，速度慢，支持同城跨行
                    tmpXElement.addChild(new XElement("transFlag", "1"));
                    tmpXElement.addChild(new XElement("transmitType", "1"));
                } else {
                    //电汇，速度快，收费，直通同城跨行，非同城跨行
                    tmpXElement.addChild(new XElement("transFlag", "2"));
                    tmpXElement.addChild(new XElement("transmitType", "2"));
                }
                //加急时直接走电汇渠道，速度快，但是收费
                if (p_req1908.singleDetail.paySpd.equals("1")) {
                    tmpXElement.addChild(new XElement("transFlag", "2"));
                    tmpXElement.addChild(new XElement("transmitType", "2"));
                }
            }
        }

        //0：企业；1：个人
        if (p_req1908.singleDetail.isPrivate.equals("1")) {
            tmpXElement.addChild(new XElement("recDepType", "1"));
        } else {
            tmpXElement.addChild(new XElement("recDepType", "0"));
        }

        String isAgreeFlag = getBankConfig().getValueAsString("isAgreeFlag","1");
        tmpXElement.addChild(new XElement("isAgreeFlag", isAgreeFlag));
        tmpXElement.addChild(new XElement("remark1", "0"));
        tmpXElement.addChild(new XElement("remark2", "0"));
        tmpXElement.addChild(new XElement("remark3", "0"));
        tmpXElement.addChild(new XElement("remark4", "0"));
        nodeAnalysis(p_req1908.singleDetail.srcXElement, tmpXElement, getCharset());
        xmlWriter.writeXElement(tmpXElement);
        xmlWriter.writeEndDocument();

        String[] tmpStrRet = sendToBank(xmlWriter.toXmlString(), opName);//发送银行

        if (tmpStrRet[0].length() == 0) {
            StringBuilder tmpSbMsg = new StringBuilder();
            //解析银行返回
            XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
            if (tmpBkReader != null) {
                String RETURN_CODE = tmpBkReader.getFirstText("/BCCBEBankData/opRep/retCode");
                String RETURN_MSG = tmpBkReader.getFirstText("/BCCBEBankData/opRep/errMsg");

                retDetail.respCode = "0";
                retDetail.reqSeqID = tmpBkReader.getFirstText("/BCCBEBankData/opRep/opResult/orderSerialNo");

                if (RETURN_CODE.equals("0")) {
                    retDetail.transState = RETURN_CODE + "+"  + tmpBkReader.getFirstText("/BCCBEBankData/opRep/opResult/result");
                    retDetail.payInfoCode = retDetail.transState;
                } else {
                    retDetail.transState = RETURN_CODE;
                    retDetail.payInfoCode = RETURN_CODE;
                }
                retDetail.respInfo = RETURN_MSG;
            } else {
                retDetail.respCode = "-1";
                retDetail.respInfo = tmpSbMsg.toString();
            }
        } else if (tmpStrRet[0].equals(ConnState.FAIL)) {
            retDetail.respCode = "0";
            retDetail.respInfo = tmpStrRet[1];
            retDetail.reqSeqID = p_req1908.singleDetail.askNumber;
            retDetail.transState = PaymentState.FAIL_Payment;
            retDetail.payInfoCode = tmpStrRet[0];
        } else {
            retDetail.respCode = "-1";
            retDetail.respInfo = tmpStrRet[1];
        }
        return retDetail;
    }

    //1944 状态查询
    public RetAtsSingle d_1944_QrySglPay(ReqQrySingle p_req1944) throws Exception {
        //返回ATS的对象
        RetAtsSingle retAts = new RetAtsSingle(p_req1944.reqHeader);

        RetAtsSglDetail tmpRetAtsDetail = new RetAtsSglDetail();

        XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
        xmlWriter.autoFormat = false;
        writeCommonHeader(xmlWriter);//写入通用的头部节点
        String opName = "CebankQryOrderOp";
        xmlWriter.writeStartElement("opReq");
        xmlWriter.writeElementString("opName", opName);
        xmlWriter.writeElementString("serialNo", p_req1944.askNumber);
        xmlWriter.writeElementString("reqTime", Format.Date8Format.format(new Date()));
        xmlWriter.writeStartElement("ReqParam");
        xmlWriter.writeElementString("orderSerialNo", p_req1944.askNumber);
        xmlWriter.writeEndElement();
        xmlWriter.writeEndElement();
        xmlWriter.writeEndDocument();
        try {

            String[] tmpStrRet = sendToBank(xmlWriter.toXmlString(), opName);
            if (tmpStrRet[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                if (tmpBkReader != null) {
                    String RETURN_CODE = tmpBkReader.getFirstText("/BCCBEBankData/opRep/retCode");
                    String RETURN_MSG = tmpBkReader.getFirstText("/BCCBEBankData/opRep/errMsg");

                    tmpRetAtsDetail.respCode = "0";
                    tmpRetAtsDetail.reqSeqID = tmpBkReader.getFirstText("/BCCBEBankData/opRep/opResult/orderSerialNo");

                    tmpRetAtsDetail.transAmt = tmpBkReader.getFirstText("/BCCBEBankData/opRep/opResult/payAmt");

                    if (RETURN_CODE.equals("0")) {
                        tmpRetAtsDetail.transState = RETURN_CODE + "+" + tmpBkReader.getFirstText("/BCCBEBankData/opRep/opResult/result");
                        tmpRetAtsDetail.payInfoCode = tmpRetAtsDetail.transState;
                    } else {
                        tmpRetAtsDetail.transState = RETURN_CODE;
                        tmpRetAtsDetail.payInfoCode = RETURN_CODE;
                    }
                    tmpRetAtsDetail.respInfo = RETURN_MSG;
                } else {
                    tmpRetAtsDetail.respCode = "-1";
                    tmpRetAtsDetail.respInfo = tmpSbMsg.toString();
                }
            } else {
                tmpRetAtsDetail.respCode = "-1";
                tmpRetAtsDetail.respInfo = tmpStrRet[1];
            }
        } catch (Exception e) {
            tmpRetAtsDetail.respCode = "-1";
            tmpRetAtsDetail.respInfo = e.getMessage();
            e.printStackTrace();
        }

        retAts.writeRetDetail(tmpRetAtsDetail);
        return retAts;
    }

    @Override
    public RetAtsSingleBat d_1944BAT_QrySglBatPay(ReqQrySingleBat p_req1944BAT) throws Exception {
        return null;
    }
}
